# Definition for a binary tree node.
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
from collections import deque
from math import inf
from typing import List, Optional


class Solution:
    def largestValues(self, root: Optional[TreeNode]) -> List[int]:
        queue = deque()
        queue.append(root)
        ans = []
        while len(queue) > 0:
            sz = len(queue)
            maxValue = -inf
            for i in range(sz):
                node = queue.popleft()
                if node is None:
                    continue
                if node.val > maxValue:
                    maxValue = node.val
                if node.left is not None:
                    queue.append(node.left)
                if node.right is not None:
                    queue.append(node.right)
            if maxValue != -inf:
                ans.append(maxValue)

        return ans